package tiny

import (
	//"github.com/17683954109/Tiny_GO/config"
	"github.com/17683954109/Tiny_GO/router"
	"encoding/json"
	"io"
	"log"
	"net/http"
)

/*
init : init FrameWork Config
*/
func init() {
	//config.Conf.Init()
}

/*
RouteTable
*/
var _routeList router.RouteList

/*
Worker : Uri Send To CallBack And Response No Handle Uri
*/
func worker(w http.ResponseWriter, r *http.Request) {
	found := false
	for _, v := range _routeList.List {
		if v.Uri == r.URL.Path && r.Method == v.Method {
			found = true
			v.RunnerNum++
			v.CallBack(w, r)
			v.RunnerNum--
		}
	}
	if !found {
		notFound(w, r)
	}
}

/*
ListenAndServe : Start Listen Port And Serve Client With Http
*/
func listenAndServe(routeList router.RouteList, port string) {
	_routeList = routeList
	http.HandleFunc("/", worker)
	log.Fatal(http.ListenAndServe(port, nil))
}

/*
NotFound : Default Response
*/
func notFound(w router.Writer, r router.Request)  {
	http.NotFound(w, r)
}

/*
String : Response String Msg To Client
*/
func String(str string, w router.Writer){
	_, err := io.WriteString(w, str)
	if err != nil {
		http.Error(w, "Server Error", 500)
	}
}

/*
Json : Response Json Msg To Client
*/
func Json(val interface{}, w router.Writer)  {
	res, err := json.Marshal(val)
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Server", "Tiny_GO 0.1.15")
	_, err = io.WriteString(w, string(res))
	if err != nil {
		http.Error(w, "Server Error", 500)
	}
}

/*
SetHeader : Set Response Header
*/
func SetHeader(w router.Writer, key string, value string)  {
	w.Header().Set(key, value)
}

/*
Run : ListenAndServe To A Port
*/
func Run(port string) {
	_routeList := router.GetRoute()
	listenAndServe(_routeList, port)
}
